package com.common.android.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.entity.mime.content.ByteArrayBody;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

/**
 * 图片处理相关的类
 * <br>Created 2014-8-20 下午9:03:25
 * @version  1.0
 * @author   luojw		
 * @see 	 
 * Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
 *
 */
public class ImageUtils {
    
    /**
     * 图片参数
     * 
     * <br>Created 2014-10-9 下午5:18:54
     * @version  ImageUtils
     * @author   huangszh		
     *
     * @see 	 
     * 
     * Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
     *
     */
    public static class ImageUploadProcessParams {
        
        public int wifi_height = 1024;
        public int wifi_width = 1920;
        public int no_wifi_height = 600;
        public int no_wifi_width = 640;
        public int compress_quality = 80;//微博图片 压缩率改成 80，  by dyf 20140119
    }

    private final static String TAG = "ImageUtils";
    private final static int ROTATE_90 = 90;
    private final static int ROTATE_180 = 180;
    private final static int ROTATE_270 = 270;
    /**
     * 根据路径判断图片文件是否可用
     * <br>Created 2014-3-18下午5:41:24 
     * @param path 图片路径
     * @return 图片文件可用返回true，否则返回false
     * @author       cb
     */
    public static boolean isBitmapFileAvaiable(String path){
        if (TextUtils.isEmpty(path)){
            return false;
        }
        try {
            Options options = new Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            if (options.outHeight > 0 && options.outWidth > 0){
                Bitmap bmp = BitmapFactory.decodeFile(path);
                if (bmp != null) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace(); 
        }
        return false;
    }
    
    /**
     * 回收图片
     * <br>Created 2014-3-24下午2:05:32
     * @param bitmap 要回收的位图
     * @author       cb
     */
    public static void recycleBitmap(Bitmap bitmap) {
        if (bitmap != null) {
            android.util.Log.d("bitmap", "recycle bitmap:" + bitmap);
            bitmap.recycle();
            bitmap = null;
        }
    }
    
    /**
     * 判断某个图片是否GIF格式 
     * <br>Created 2014-3-24下午2:10:14 
     * @param path 图片路径
     * @return 图片是GIF格式返回true,否则返回false
     * @author       cb
     */
    public static boolean isGifFile(String path){
        final int HEAD_COUNT = 3; //gif扩展名的长度
        if (TextUtils.isEmpty(path)){
            return false;
        }
        boolean isGif = false;
        InputStream stream = null;
        try {
            stream = new FileInputStream(path);
            byte[] head = new byte[HEAD_COUNT];
            stream.read(head);
            String imgType = new String(head);
            isGif = imgType.equalsIgnoreCase("gif");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream!=null){
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }               
            }
        }
        return isGif;
    }
   
    /**
     * 判断某个图片是否GIF格式 
     * <br>Created 2014-3-24下午8:52:26
     * @param imageExt 图片文件名
     * @param url 原始url
     * @return 图片是Gif格式返回true，否则放回false
     * @author       chenqian
     */
    @SuppressLint("DefaultLocale")
    public static boolean isGifForWeibo(String imageExt, String url){
        if(!TextUtils.isEmpty(imageExt) && TextUtils.equals(imageExt.toLowerCase(), "gif")){
            return true;
        }
        return ImageUtils.isGifPicture(url);
    }
    
    /**
     * 判断url是否Gif图片
     * <br>Created 2013-12-16下午15:20:06
     * @param strFile 原始url
     * @return url是Gif图片是返回true，否则放回false
     * @author       chenqian
     */
    @SuppressLint("DefaultLocale")
    public static boolean isGifPicture(String strFile) {
        if (!TextUtils.isEmpty(strFile) 
                && (strFile.toLowerCase().endsWith(".gif") 
                || strFile.toLowerCase().contains(".gif&"))) {
            return true;
        }
        return false;
    }
    
    /**
     * 获取形象照
     * <br>Created 2014-8-22 上午9:57:24
     * @param path 图片路径
     * @param w 获取图片宽度
     * @param h 获取图片高度
     * @return 返回获取的Bitmap图片
     * @author       huangyx
     */
    public static Bitmap loadLocalBitmapRoughScaled(String path, int w, int h) {
        Bitmap bm = null;

        try {
            BitmapFactory.Options options = new BitmapFactory.Options();

            options.inJustDecodeBounds = true;
            options.inTempStorage = new byte[32 * 1024];
            // 获取这个图片的宽和高
            bm = BitmapFactory.decodeFile(path, options); // 此时返回bm为空

            options.inJustDecodeBounds = false;
            
            int wa = options.outHeight / h;
            int ha = options.outWidth / w;
            int  be = wa;
            if (wa > ha) {
                be = ha;
            }
            if (be <= 0) {
                be = 1;
            }

            options.inSampleSize = be;
            if (bm != null && !bm.isRecycled()) {
                bm.recycle();
                bm = null;
                System.gc();
            }
            bm = BitmapFactory.decodeFile(path, options);
            bm = zoomBitmap(bm,w,h);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            bm = null;
        }
        return bm;
    }
    
    /**
     * 上传和修改个人头像   
     * <br>Created 2014-8-22 上午9:56:24
     * @param path 图片的路径
     * @param maxsize 图片的最大高度
     * @return 返回获取的Bitmap图片
     * @author       huangyx
     */
    public static Bitmap loadLocalBitmapRoughScaled(String path, int maxsize) {
        Bitmap bm = null;

        try {
            BitmapFactory.Options options = new BitmapFactory.Options();

            options.outHeight = maxsize;
            options.inJustDecodeBounds = true;
            options.inTempStorage = new byte[32 * 1024];
            // 获取这个图片的宽和高
            bm = BitmapFactory.decodeFile(path, options); // 此时返回bm为空

            options.inJustDecodeBounds = false;
            int be = options.outHeight / (int)(maxsize / 10);
            if (be % 10 != 0) {
                be += 10;
            }

            be = be / 10;
            if (be <= 0) {
                be = 1;
            }

            options.inSampleSize = be;
            if (bm != null && !bm.isRecycled()) {
                bm.recycle();
                bm = null;
                System.gc();
            }
            bm = BitmapFactory.decodeFile(path, options);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            bm = null;
        }
        return bm;
    }
    
    /**
     * 压缩bitmap图片
     * <br>Created 2014-8-22 上午10:11:27
     * @param bitmap 原始bitmap
     * @param size 长或宽的最大长度
     * @return 压缩后的bitmap
     * @author       huangyx
     */
    public static Bitmap compress(Bitmap bitmap, int size) {
        if (bitmap == null) {
            return null;
        }
        if (bitmap.isRecycled()) {
            return null;
        }
        // create explicit picture
        int max = bitmap.getHeight();
        int min = bitmap.getHeight();
        if (bitmap.getWidth() > bitmap.getHeight()) {
            max = bitmap.getWidth();
        }
        if (bitmap.getWidth() < bitmap.getHeight()) {
            min = bitmap.getWidth();
        }
        min = size * min / max;
        max = size;
        if (bitmap.getWidth() > bitmap.getHeight()) {
            bitmap = Bitmap.createScaledBitmap(bitmap, max, min, false);
        } else {
            bitmap = Bitmap.createScaledBitmap(bitmap, min, max, false);
        }
        return bitmap;
    }
    
    /**
     * 
     * <br>Created 2014-8-22 上午10:14:47
     * @param path 图片路径
     * @param size 图片大小
     * @return bitmap
     * @author       huangyx
     */
    public static Bitmap loadLocalBitmapExactScaled(String path, int size) {
        Bitmap bm = loadLocalBitmapRoughScaled(path, size * 2);
        if (bm == null) {
            return bm;
        }
        // rotate from exif
        int degree = getDegree(path);
        bm = rotateBitmap(bm, degree);
        return compress(bm, size);
    }
    
    /**
     * 
     * 
     * <br>Created 2014-8-22 上午10:17:45
     * @param path 图片路径
     * @param size 图片大小
     * @return bitmap
     * @author       huangyx
     */
    public static Bitmap  compressBitmap(String path, int size){
         Bitmap bm = loadLocalBitmapRoughScaled(path, size * 2);
         return bm;
    }
    
    /**
     * 压缩和旋转图片
     * <br>Created 2014-8-22 上午10:18:38
     * @param path 图片路径
     * @author       huangyx
     */
    public static void scaleAndRotateImage(String path){
        FileOutputStream out = null;
        Bitmap bitmap = null;
        
        try { 
            BitmapFactory.Options options = new BitmapFactory.Options();

            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            
            // 获得原尺寸
            int mWidth = options.outWidth;
            // 获得输出宽边长
            int sWidth = 1280;
            // 未缩放的情况：1.拍照尺寸<=设置质量尺寸;2.为高质量，保存原图
            // 计算压缩比例
            int s = Math.round((float) mWidth / (float) sWidth);
            if (sWidth == 0) {
                s = 1;
            }
            if (s < 1) {
                s = 1;
            }
            // =1 压缩经常会崩溃
            if (s > 1) {
                // 生成压缩
                options.inSampleSize = s;
            }
            options.inJustDecodeBounds = false;
    
           try {
                bitmap = BitmapFactory.decodeFile(path, options);
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                bitmap = null;
            }
            if (bitmap == null) {
                // 读取失败，压缩读取
                options.inSampleSize = 2;
                bitmap = BitmapFactory.decodeFile(path, options);
            }
            if (bitmap == null) {
                // 依然失败 ，不处理
                return;
            }
            // rotate from exif
            int degree = getDegree(path);
            bitmap = rotateBitmap(bitmap, degree);
            out = new FileOutputStream(new File(path));
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)) {
                out.flush();
            }
        } catch (OutOfMemoryError err) {
            err.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
        }
    }
    
    /**
     * 把图片存到SD卡
     * <br>Created 2014-8-22 上午10:20:16
     * @param bitmap 源bitmap
     * @param path 存入SD卡的路劲
     * @author       huangyx
     */
    public static void  writeBitmap2SD(Bitmap bitmap, String path){
        FileOutputStream out = null;
        try{        
            out = new FileOutputStream(new File(path));
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)) {
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
        }
    }
    
    /**
     * 获取图片旋转角度
     * <br>Created 2014-8-22 上午10:23:39
     * @param filename 图片路径
     * @return 旋转的角度
     * @author       huangyx
     */
    public static int getDegree(String filename) {
        int result = 0;
        int orientation = 0;
        try {
            ExifInterface exif = new ExifInterface(filename);
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);

        } catch (Exception e) {
            e.printStackTrace();
        }

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                result = ROTATE_90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                result = ROTATE_180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                result = ROTATE_270;
                break;
        default:
            break;
        }
        //rotate
        return result;
    }

    /**
     * 旋转bitmap
     * <br>Created 2011-4-1上午10:23:00
     * @param bitmap 要旋转的bitmap
     * @param degree 旋转的度数
     * @return 旋转之后的bitmap
     * @author       hexy
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degree) {
        if (degree == 0) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            Bitmap tempBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap
                    .getHeight(), matrix, true);

            // Bitmap操作完应该显示的释放
            bitmap.recycle();
            bitmap = tempBmp;
        } catch (OutOfMemoryError ex) {
            // Android123建议大家如何出现了内存不足异常，最好return 原始的bitmap对象
            ex.printStackTrace();
        }
        return bitmap;
    }
    
    /**
     * 放大或缩小bitmap
     * <br>Created 
     * @param bitmap 要进行放大或缩小的bitmap
     * @param w 放大或缩小后的宽度
     * @param h 放大或缩小后的高度
     * @return 完成放大或缩小的bitmap
     * @author       huangyx
     */
    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) w / width);
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newBmp;
    }
    
    /**
     * 根据图片URI获取本地存放路径
     * <br>Created 2013-12-25下午2:58:05
     * @param context 应用的context
     * @param imageUri 图片的URI
     * @return 图片本地存放路径，图片不存在则返回null
     * @author       huangszh
     */
    public static String getImgLocalPathByUri(Context context, Uri imageUri){
        if (imageUri == null) {
            return null;
        }
        // 获取文件的绝对路径  相册
        String path = "";
        String[] projection = { MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE };
        Cursor cursor = MediaStore.Images.Media.query(context.getContentResolver(), imageUri, projection);
        try {                        
            if (cursor != null && cursor.moveToNext()) {
                path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
            } else {                    //小米1
                path = imageUri.getPath();
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }
    
    /**
     * 判断是否图片
     * <br>Created 2014-8-22 下午2:01:34
     * @param strFile 文件路径
     * @return 是图片返回true，否则返回false
     * @author       huangszh
     */
    public static boolean isImage(String strFile){
        String[] photoSuffixes = new String[] { ".png", ".jpg", ".gif"}; // 注意英文字母全部用小写
        for (String suffix : photoSuffixes) {
            if (strFile.endsWith(suffix)) {
                return true;
            }
        }       
        return false;
    }
    
    /**
     * 从文件获取bitmap
     * <br>Created 2014-8-22 下午2:06:34
     * @param filename 文件路径
     * @param reqWidth 图片宽度
     * @param reqHeight 图片高度
     * @return 放回bitmap
     * @author       huangyx
     */
    public static Bitmap decodeSampledBitmapFromFile(String filename,
            int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filename, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filename, options);
    }
   
    /**
     * 限定最大宽的等比缩小原图，比例超过maxRate的返回null,最大宽度不超过reqMaxWidth
     * <br>Created 2013-11-29下午3:59:25
     * @param path 文件路径
     * @param reqMaxWidth 限定最大宽
     * @param maxRate 缩小比例
     * @return 缩小后的bitmap
     * @author       daiyf
     */
   public static Bitmap decodeSampledBitmapFromFile(String path,
           int reqMaxWidth, double maxRate) {

       // First decode with inJustDecodeBounds=true to check dimensions
       final BitmapFactory.Options options = new BitmapFactory.Options();
       options.inJustDecodeBounds = true;
       BitmapFactory.decodeFile(path, options);
       double rate = 0;
       if(options.outWidth < options.outHeight) {
           rate = options.outHeight/options.outWidth;
       } else {
           rate = options.outWidth/options.outHeight;
       }
       //比例超过限制返回空
       if(rate > maxRate) {
           return null;
       }

       // Calculate inSampleSize
       options.inSampleSize = 1;
       int orgWidth = 0;
       if(options.outHeight > options.outWidth) {
           orgWidth = options.outHeight;
       } else {
           orgWidth = options.outWidth;
       }
       if(orgWidth > reqMaxWidth) {
           options.inSampleSize = orgWidth/reqMaxWidth;
           
           if(orgWidth%reqMaxWidth > 0) {
               options.inSampleSize++;
           }
       }
       options.inJustDecodeBounds = false;
       return BitmapFactory.decodeFile(path, options);
   }
       
   /**
    * 计算图片缩小比例
    * <br>Created 2014-8-22 下午2:16:47
    * @param options 
    * @param reqWidth 要求宽度
    * @param reqHeight 要求高度
    * @return 图片缩小比例
    * @author       huangyx
    */
    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        int tagwidth; // 目标宽度
        int orgwidth; // 原始宽度
        int inSampleSize = 1;// 初始采样比为1
        // 取宽高中较小的设置为原始宽度
        if(options.outHeight > options.outWidth){
            orgwidth = options.outWidth;
        } else {
            orgwidth = options.outHeight;
        }
        // 取目标宽高 中较小的设置为目标宽度
        if(reqHeight > reqWidth){
            tagwidth = reqWidth;
        } else {
            tagwidth = reqHeight;
        }

        // 如果原始宽度 大于 目标宽度则需要压缩
        if (orgwidth > tagwidth) {
            inSampleSize = Math.round((float) orgwidth / (float) tagwidth);
            final float totalPixels = options.outWidth * options.outHeight;
            final float totalReqPixelsCap = reqWidth * reqHeight * 2;
            while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
                inSampleSize++;
            }
        }
        return inSampleSize;
    }
    /**
     * 获取上传图片的ByteArrayBody
     * <br>Created 2014-8-22 下午1:51:31
     * @param context   上下文
     * @param file  上传图片
     * @param params 压缩处理参数
     * @return  返回ByteArrayBody对象，处理错误或者无可用网络返回null
     * @author       huangszh
     */
    @SuppressLint("DefaultLocale")
    public static ByteArrayBody getImageByteArrayBody(Context context,File file,
            ImageUploadProcessParams params) {
        
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);//获取系统的连接服务
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();//获取网络的连接情况  
        
        if(file == null || activeNetInfo == null) {
            return null;
        }
        
        if(null != file && file.getName().toLowerCase().endsWith(".gif")) {
            return convertGIFToByteArray(file);
        } else {
            if(activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI){
                // wifi
                return compressAndRotate(file, params.wifi_width,
                        params.wifi_height, params.compress_quality);
            } else {
                // 非wifi
                return compressAndRotate(file, params.no_wifi_width, 
                        params.no_wifi_height,params.compress_quality);
            }
        }
    }
    
    /**
     * 获取上传图片的ByteArrayBody，使用默认的压缩参数#ImageUploadProcessParams
     * <br>Created 2014-8-22 下午1:53:05
     * @param context 上下文
     * @param file 上传图片
     * @return  返回ByteArrayBody对象，处理错误或者无可用网络返回null
     * @author       huangszh
     */
    public static ByteArrayBody getImageByteArrayBody(Context context,File file) {
        
        return getImageByteArrayBody(context, file, new ImageUploadProcessParams());
    }
    
    /**
     * 压缩旋转图片
     * <br>Created 2014-8-22 下午1:53:48
     * @param file 图片
     * @param width 图片压缩宽度
     * @param height 图片压缩高度
     * @param quality 压缩系数，取值：0-100
     * @return 返回ByteArrayBody对象，处理错误或者无可用网络返回null
     * @author       huangszh
     */
    public static ByteArrayBody compressAndRotate(File file,int width,int height,int quality) {
        if (!file.exists()) {
            return null;
        }
        
        CompressFormat cf;
        
        //根据宽高判断是否需要采样和压缩
        Bitmap resizeBitmap = decodeSampledBitmapFromFile(file.getPath(), width, height);
        cf = CompressFormat.JPEG;
        //Log.i("upload","resizeBitmap width = " + resizeBitmap.getWidth());
        int degree = getDegree(file.getPath());
        // 如果旋转角度 > 0,则需要旋转回正确的方向
        if (degree > 0) {
            resizeBitmap = rotateBitmap(resizeBitmap, degree);
        }
        
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        
        resizeBitmap.compress(cf, quality, bos);
        resizeBitmap.recycle();
        String name =  file.getName();
        if(!isImage(name)){
            name += ".jpg";
        }
        ByteArrayBody body = new ByteArrayBody(bos.toByteArray(),name);
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }
    
    /**
     * gif转成ByteArrayBody
     * <br>Created 2014-8-22 下午2:00:05
     * @param file gif图
     * @return 返回ByteArrayBody对象，处理错误或者无可用网络返回null
     * @author       huangszh
     */
    public static ByteArrayBody convertGIFToByteArray(File file) {
        if (!file.exists()) {
            return null;
        }

        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for (int readNum; (readNum = fis.read(buf)) != -1; ) {
                bos.write(buf, 0, readNum); //no doubt here is 0
                //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
            }
            
            String name =  file.getName();
            if(!ImageUtils.isImage(name)){
                name += ".gif";
            }
            ByteArrayBody body = new ByteArrayBody(bos.toByteArray(),name);
            return body;
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e) {        
            e.printStackTrace();
        } finally{
            try {
                if(null != fis){
                    fis.close();
                }
                if(null != bos){
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }   
        }
        return null;
    }
    
    /**
     * 将文件转为ByteArrayBody
     * <br>Created 2014-8-22 下午2:00:51
     * @param file 文件
     * @return 返回ByteArrayBody对象，处理错误或者无可用网络返回null
     * @author       huangszh
     */
    public static ByteArrayBody tansferToByteArray(File file) {
        if (!file.exists()) {
            return null;
        }
        FileInputStream stream = null;
        ByteArrayOutputStream out = null;
        try {
            stream = new FileInputStream(file);
            out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1) {
                out.write(b, 0, n);
            }
            return new ByteArrayBody(out.toByteArray(), file.getName());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    } 
    
    /**
     * 
     * @param context
     * @param id
     * @param defaultId
     * @return
     */
    public static Bitmap drawableToBitmap(Context context, int id, int defaultId) {
		try{
			return BitmapFactory.decodeResource(context.getResources(), id);
		}
		catch(OutOfMemoryError e){
			System.gc();
		}
		return BitmapFactory.decodeResource(context.getResources(), defaultId);
	}
    
    /**
     * 
     * @param bitmap
     * @return
     */
    public static Bitmap toGrayImage(Bitmap bitmap) {
		Bitmap grayImg = null;
		if(bitmap==null) return bitmap;
		try {
			int width = bitmap.getWidth();
			int height = bitmap.getHeight();
			grayImg = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(grayImg);
			Paint paint = new Paint();
			ColorMatrix colorMatrix = new ColorMatrix();
			colorMatrix.setSaturation(0);
			ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(colorMatrix);
			paint.setColorFilter(colorMatrixFilter);
			canvas.drawBitmap(bitmap, 0, 0, paint);
		} catch (Exception e) {
			@SuppressWarnings("unused")
			String msg = e.getMessage();
			e.printStackTrace();
		}
		return grayImg;
	}
}
